<?php
namespace App\Http\Controllers;
use App\Exceptions\ValidateException;
use App\Repository\Contracts\SettingInterface;
use Illuminate\Http\Request;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-01-17 20:13
 *
 * @Description: 设置
 */
class SettingController extends Controller
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var SettingInterface
     */
    protected $setting;

    /**
     * SettingController constructor.
     * @param Request $request
     * @param SettingInterface $setting
     */
    public function __construct(Request $request, SettingInterface $setting)
    {
        $this->request = $request;

        $this->setting = $setting;
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $list = $this->setting->lists();

        return $this->success($list);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id)
    {
        $detail = $this->setting->detail($id);
        $detail['config'] = json_decode($detail->config, true);

        return $this->success($detail);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function created()
    {
        try {
            $form = $this->request->only(['storeName', 'shopkeeper', 'phone', 'tel', 'address']);
            $data['name'] = $this->request->input('name', null);
            $data['config'] = json_encode($form);
            $id = $this->setting->created($data);

            return $this->success($id);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * Update
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function updated($id)
    {
        try {
            $form = $this->request->only(['storeName', 'shopkeeper', 'phone', 'tel', 'address']);
            $data['name'] = $this->request->input('name', null);
            $data['config'] = json_encode($form);
            $result = $this->setting->updated($id, $data);

            return $this->success($result);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }
}